<template>
  <div class="organize" v-loading="loading">
    <el-row class="organize_dept">
      <el-col>
        <span class="dept_title">{{cacheDept.dept_name || '部门'}}</span>
        <i class="iconfont ali-bianji" @click="openDept"></i>
      </el-col>
      <el-col>
        <span class="company_name">{{companyName || '公司'}}</span>
        <i class="iconfont ali-jiantou"></i>
        <span class="dept_name">{{cacheDept.dept_name || '部门'}}</span>
      </el-col>
    </el-row>
    <el-row class="organize_title">
      <el-col :span="6">
        <span>下级部门</span>
      </el-col>
      <el-col :span="18">
        <el-button type="primary" size="mini" class="btn" @click="openChildDept" plain>添加部门</el-button>
      </el-col>
    </el-row>
    <el-row class="organize_tag">
      <div v-for="dept in cacheDept.children" :key="dept.id">
        <el-col class="organize_bottom">
          <el-button class="tag_btn" type="text" @click="findDeptUserList(dept)">
            <span>{{dept.dept_name}}</span>
            <i class="iconfont ali-jiantou"></i>
          </el-button>
        </el-col>
      </div>
    </el-row>
    <!-- <el-row>
      <el-col :span="4" :offset="10" class="load_more">
        <el-button class="more_btn" type="text">点击加载更多</el-button>
        <i class="iconfont ali-iconfontjiantou"></i>
      </el-col>
    </el-row> -->
    <el-row class="organize_title">
      <el-col :span="6">
        <span>部门人员</span>
        <i class="iconfont ali-jiantou"></i>
      </el-col>
      <el-col :span="18">
        <!-- <el-button type="danger"  size="mini" class="btn" plain @click="batchDelMember">批量删除</el-button> -->
        <el-button type="warning" size="mini" class="btn" plain @click="reviseDept">调整部门</el-button>
        <!-- <el-button type="success" size="mini" class="btn" plain @click="upload">导入/导出</el-button> -->
        <el-upload
          class="btn"
          action="/api/user/export"
          name="export_file"
          :before-upload="beforeUpload"
          :on-success='handleHaveSuccess'
          :show-file-list="false"
          >
          <el-button type="success" size="mini" plain>成员导入</el-button>
        </el-upload>
        <el-button type="primary" size="mini" class="btn" plain @click="openAdd">添加成员</el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-table :data="deptUserList" stripe style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="user_name" label="姓名"></el-table-column>
        <!-- <el-table-column prop="job" label="职位"></el-table-column> -->
        <el-table-column prop="work_num" label="工号"></el-table-column>
        <el-table-column prop="phone" label="手机"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column fixed="right" label="操作" align="center">
          <template slot-scope="scope">
            <!-- 1为停用,0为正常 -->
            <el-button @click.native.prevent="openPerson(scope.row)" type="text" size="small">编辑</el-button>
            <el-button v-if="scope.row.user_status == 0" @click.native.prevent="editStatus(scope.row,1)" type="text" size="small">停用</el-button>
            <el-button v-if="scope.row.user_status == 1" @click.native.prevent="editStatus(scope.row,0)" type="text" size="small">解冻</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <!-- 添加成员模态框 -->
    <section>
      <el-dialog :title="addUserForm.title" :visible.sync="isShow.add" width="600px">
        <el-form :model="addUserForm" style="padding:0 40px;" ref="addUserForm">
          <el-form-item label="姓名" :label-width="formLabelWidth" prop="user_name" :rules="filter_rules({required:true})">
            <el-input @blur.prevent="checkFormBlur('user_name')" v-model.trim="addUserForm.user_name" placeholder="请输入姓名"></el-input>
          </el-form-item>
          <el-form-item label="部门名称" :label-width="formLabelWidth">
            <el-tag v-for="dept in addUserForm.depts" :key="dept.id" style="margin-right:6px;">{{dept.label}}</el-tag>
            <el-button size="mini" type="text" icon="iconfont ali-add" circle @click="openDeptModal"></el-button>
          </el-form-item>
          <el-form-item label="手机" :label-width="formLabelWidth" prop="phone" :rules="filter_rules({required:true,type:'mobile'})">
            <el-input @blur.prevent="checkFormBlur('phone')" v-model.trim="addUserForm.phone" placeholder="请输入手机号"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email" :rules="filter_rules({type:'email'})">
            <el-input @blur.prevent="checkFormBlur('email')" v-model.trim="addUserForm.email" placeholder="请输入邮箱"></el-input>
          </el-form-item>
          <el-form-item label="工号" :label-width="formLabelWidth">
            <el-input v-model="addUserForm.work_num" placeholder="请输入工号"></el-input>
          </el-form-item>
          <el-form-item label="性别" :label-width="formLabelWidth">
            <el-radio v-model="addUserForm.sex" :label="1">男</el-radio>
            <el-radio v-model="addUserForm.sex" :label="0">女</el-radio>
          </el-form-item>
          <el-form-item label="生日" :label-width="formLabelWidth">
            <el-date-picker v-model="addUserForm.birthday" value-format="yyyy-MM-dd" type="date" placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="入职时间" :label-width="formLabelWidth">
            <el-date-picker v-model="addUserForm.entry_date" value-format="yyyy-MM-dd" type="date" placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="前台可以登陆" :label-width="formLabelWidth">
            <el-radio v-model="addUserForm.reception_islogin" :label="0">否</el-radio>
            <el-radio v-model="addUserForm.reception_islogin" :label="1">是</el-radio>
          </el-form-item>
          <el-form-item label="后台可以登陆" :label-width="formLabelWidth">
            <el-radio v-model="addUserForm.backstage_islogin" :label="0">否</el-radio>
            <el-radio v-model="addUserForm.backstage_islogin" :label="1">是</el-radio>
          </el-form-item>
          <el-form-item :label="field.reservefield_name" :label-width="formLabelWidth" v-for="(field,i) in reservefield" :key="field.id">
            <el-input v-model="cacheFields[i].reservefield_value" placeholder="请输入"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="isShow.add = false">取 消</el-button>
          <el-button type="primary" :disabled="exist.show" @click="validate('addUserForm')">{{exist.msg}}</el-button>
        </span>
      </el-dialog>
    </section>
    <!-- 编辑部门模态框 -->
    <section>
      <el-dialog title="编辑部门" :visible.sync="isShow.dept" width="600px">
        <el-form :model="editDeptForm" style="padding:0 40px;" ref="editDeptForm">
          <el-form-item label="部门名称" :label-width="formLabelWidth" prop="dept_name" :rules="filter_rules({required:true})">
            <el-input v-model="editDeptForm.dept_name"></el-input>
          </el-form-item>
          <!-- <el-form-item label="上级部门" :label-width="formLabelWidth">
            <el-input v-model="cacheDept.dept_name" disabled></el-input>
          </el-form-item> -->
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="isShow.dept = false">取 消</el-button>
          <el-button type="danger" @click="delDept">删 除</el-button>
          <el-button type="primary" @click="validate('editDeptForm')">确 定</el-button>
        </span>
      </el-dialog>
    </section>
    <!-- 添加子部门 -->
    <section>
      <el-dialog title="添加子部门" :visible.sync="isShow.child" width="600px">
        <el-form :model="addChildDept" style="padding:0 40px;" ref="addChildForm">
          <el-form-item label="部门名称" :label-width="formLabelWidth" prop="dept_name" :rules="filter_rules({required:true})">
            <el-input v-model="addChildDept.dept_name"></el-input>
          </el-form-item>
          <el-form-item label="上级部门" :label-width="formLabelWidth">
           <el-select clearable v-model="addChildDept.parent_id" placeholder="请选择部门" style="width: 380px">
            <el-option
              v-for="(item,i) in deptList" :key="i"
              :label="item.dept_name" :value="item.id">
            </el-option>
          </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="isShow.child = false">取 消</el-button>
          <el-button type="primary" @click="validate('addChildForm')">确 定</el-button>
        </span>
      </el-dialog>
    </section>
    <!-- 部门人员调整部门 -->
    <section>
      <dept-transfer ref="childInit" @closeTransfer="isShow.transfer = false" @getDepts="getDepts(transfer.decide, $event)" :isShow="isShow.transfer"></dept-transfer>
    </section>
  </div>
</template>
<script>
import dept_transfer from './components/edit_dept_transfer'
import { dept_edit, dept_delete, dept_save, dept_findById } from '@/api/group'
import { user_deleteAll, user_save, user_edit, user_editStatua, user_delete, user_findById, user_checkUser } from '@/api/user'
import { reservefield_listAll } from '@/api/reservefield'
import { mapGetters } from 'vuex'

export default {
  components: {'dept-transfer': dept_transfer },
  name: "organize",
  data() {
    return {
      deptList: [],
      isShow:{ add: false, dept: false, child: false, transfer: false },
      transfer: {},
      loading: false,
      editDeptForm: {}, //修改部门名称
      addUserForm: {}, //添加成员
      addForm:{},
      addChildDept: {},
      formLabelWidth:'100px',
      multipleSelection: [],
      reservefield: [],
      cacheFields: [],
      exist: {show: false, msg: '确 定'}
    };
  },
  computed:{
    ...mapGetters([
      'deptUserList','companyName','cacheDept', 'menuDeptList'
    ])
  },
  methods: {
    async checkFormBlur(field){
      console.log('11111');
      if(!this.addUserForm[field]){
        return ;
      }
      const val = {user_name: '姓名', phone: '手机', email: '邮箱'}
      let params = {company_id: localStorage.getItem('companyId') - 0};
      params[field] = this.addUserForm[field]
      const {data} = await user_checkUser(params);

      if(data.status === 100){
        if(data.data.exist === 1){
          this.exist = {show: true, msg: `${val[field]}已存在！`};
          this.$message.warning(`${val[field]}已存在！`);
        }else{
          this.exist = {show: false, msg: '确 定'};
        }
      }
    },
    handleSelectionChange(e){//
       this.multipleSelection = e;
    },
    async batchDelMember(){//批量删除
      if(this.multipleSelection.length == 0){
        this.$message.warning('请选择至少一位成员')
        return ;
      }
      try {
        let res = await this.$confirm('确认删除吗？')
        if(res == 'confirm'){
          this.loading = true ;
          let ids = '';
          for (var i = 0; i < this.multipleSelection.length; i++) {
            var element = this.multipleSelection[i];
            ids += element.id + ','
          }
          let { data } = await user_deleteAll({array: ids });
          this.loading = false ;
          if(data.status == 100){
            await this.$store.dispatch('FineUsersByDeptId', this.cacheDept.id);//重新加载默认第0条部门下的人员列表
            this.$message.success('删除成功')
          }
        }
      } catch (error) {
        console.log(error,'error')
      }
    },
    reviseDept(){//调整部门
      if(this.multipleSelection.length == 0){
        this.$message.warning('请先选择需要调整部门的人员');
        return;
      }
      this.transfer.decide = 'revise'
      this.$refs.childInit.openTransfer();
      this.isShow.transfer = true;
    },
    async editMember(e){//人员调整部门调用接口
      this.loading = true
      let ids = ""
      for (var i = 0; i < this.multipleSelection.length; i++) {
        var element = this.multipleSelection[i];
        ids = e.map(item => item.id).join()
        let params = { id: element.id, dept_ids: ids }
        console.log('params: ', params);

        await user_edit(params)
      }
      this.loading = false
      this.$message.success('修改成功')
      this.$store.dispatch('FineUsersByDeptId', this.cacheDept.id);//重新加载当前页面成员
    },
    openChildDept(){//打开添加子部门
      this.deptList = this.menuDeptList;
      this.isShow.child = true;
      this.addChildDept = {};
    },
    async delDept(){//删除部门
      try {
        let res = await this.$confirm('确认删除吗？');
        if(res == 'confirm'){
          this.isShow.dept = false;
          this.loading = true ;
          await dept_delete(this.editDeptForm);
          let dept = await this.$store.dispatch("SetDeptList");//重新加载菜单
          this.loading = false ;
          this.$store.dispatch('FineUsersByDeptId', dept[0].id);//重新加载默认第0条部门下的人员列表
          this.$store.dispatch("SetCacheDept", dept[0]);//重新加载当前选中部门的详情 包含子集
        }
      } catch (error) {
        console.log(error,'error')
      }
    },
    openDept(){//打开编辑部门模态框
      this.editDeptForm = this.cacheDept;
      this.isShow.dept = true;
    },
    async findDeptsByStrId(ids){
      let depts = []
      let arr = ids.split(',');
      for (let i = 0; i < arr.length; i++) {
        let id = arr[i];
        let {data} = await dept_findById({company_id: localStorage.getItem("companyId"), id: id})
        if(data.status === 100){
          depts.push({...data.data, label: data.data.dept_name})
        }
      }
      this.addUserForm.depts = depts;
    },
    async openPerson(e){//打开编辑人员信息模态框
      this.loading = true;
      e.title = e.user_name + `(ID:${e.id})`;
      this.addUserForm = e ;
      // this.addUserForm.depts = [this.cacheDept];
      await this.findDeptsByStrId(e.dept_ids)
      let { data } = await user_findById({id: e.id});
      if(data.status == 100){
        this.cacheFields = []
        data.data.reservefields.forEach((item,i) => {
          this.cacheFields[i] = item;
        })
      }
      this.loading = false;
      this.isShow.add = true ;
      this.transfer.decide = 'editMember';
    },
    async editStatus(e,i){
      let params = {
        id: e.id,
        user_status: i
      }
      let {data} = await user_editStatua(params)
      this.loading = true
      if(data.status == 100){
        this.loading = false
        this.$message.success(i==1?'停用成功':'解冻成功')
        await this.$store.dispatch('FineUsersByDeptId', this.cacheDept.id);//重新加载默认第0条部门下的人员列表
      } else {
        this.$message.error(data.msg)
      }
    },
    openAdd(){//打开添加成员模态框
      this.initFieldValue();//初始化备用字段val
      this.addUserForm = {backstage_islogin: 0, reception_islogin: 0, sex: 1, title: '添加成员'}
      this.transfer.decide = 'addMember'
      this.isShow.add = true;
    },
    openDeptModal(){//打开部门模态框 ----添加成员用
      this.$refs.childInit.openTransfer();
      this.isShow.transfer = true;
    },
    getDepts(e,obj){
      if(obj.length == 0){
        this.$message.warning('至少要选择一个部门')
        return ;
      }
      if(e == 'addMember' || e == 'editMember'){//添加成员||修改
        this.addUserForm.depts = obj
      }else if(e == 'revise'){//调整部门
        this.editMember(obj);
      }
      this.isShow.transfer = false;
    },
    async addMember(){//添加成员||修改
      this.isShow.add = false;
      this.addUserForm.dept_ids = this.addUserForm.depts.map( item => item.id).join();  //this.addUserForm.depts[0].id;
      this.addUserForm.company_id = localStorage.getItem("companyId");
      this.loading = true ;
      let decide = this.transfer.decide;
      this.addUserForm.reservefields = JSON.stringify(this.cacheFields);
      let result ;
        let params = {company_id: localStorage.getItem('companyId') - 0};
      if(decide == 'addMember'){
        result = await user_save(this.addUserForm, params);
      }else {
        result = await user_edit(this.addUserForm, params);
      }
      this.$store.dispatch('FineUsersByDeptId', this.cacheDept.id);//重新加载当前页面成员
      this.loading = false ;
      if(result.data.status == 100){
        this.$message.success(decide == 'addMember'? '添加成功': '编辑成功')
      }else{
        this.$message.error(result.data.msg)
      }
    },
    async editDept(){//修改部门名称
      this.loading = true ;
      let { data } = await dept_edit(this.editDeptForm);
      await this.$store.dispatch("SetDeptList");
      this.loading = false;
      if(data.status == 100){
        this.$message.success('修改成功')
      }
    },
    async addChild(){//添加子部门
      let result = {
        dept_name: this.addChildDept.dept_name,
        company_id: localStorage.getItem("companyId"),
        parent_id: this.addChildDept.parent_id || 0
      }
      this.loading = true ;
      let { data } = await dept_save(result);
      await this.$store.dispatch("SetDeptList");//重新加载菜单
      await this.$store.dispatch("SetCacheDept", this.cacheDept);//重新加载当前选中部门的详情 包含子集
      if(data.status == 100){
        this.$message.success('添加成功')
      }
      this.loading = false ;
    },
    validate(e){
      this.$refs[e].validate((valid) => {
        if (valid) {
          switch (e) {
            case 'editDeptForm': //关闭编辑
              this.isShow.dept = false
              this.editDept();
              break;
            case "add":
              this.isShow.add = false
              break;
            case "addChildForm": //添加子部门
              this.isShow.child = false ;
              this.addChild()
              break;
            case "addUserForm": //
              if(!this.addUserForm.depts || this.addUserForm.depts.length == 0){
                this.$message.warning('请选择部门')
                return;
              }
              this.addMember();
              break;
          }
        }else{
          return false;
        }
      });
    },
    beforeUpload(file){//导入
      this.loading = true;
      let name = file.name.split('.');
      if (name[name.length - 1] === 'xls' || name[name.length - 1] === 'xlsx') {
        return file
      } else {
        this.$message.error('文件只能是 xls/xlsx 格式!')
        return false
      }
    },
    handleHaveSuccess(res, file, fileList) {
      this.loading = false;
      if (res.status == 100) {
        this.$message.success("导入成功");
        this.$store.dispatch('FineUsersByDeptId', this.cacheDept.id);//重新加载当前页面成员
      }else{
        this.$message.warning("上传异常");
      }
    },
    async findDeptUserList(dept){//获取当前部门id下面的人员列表
      this.loading = true ;
      await this.$store.dispatch("SetCacheDept", dept);//设置当前选中部门的详情 包含子集
      await this.$store.dispatch('FineUsersByDeptId', dept.id);
      this.loading = false ;
    },
    async initField(){//初始化备用字段
      let { data } = await reservefield_listAll({company_id: localStorage.getItem("companyId")});
      if(data.status == 100){
        this.reservefield = data.data.rows;
        this.initFieldValue();
      }
    },
    initFieldValue(){//初始化备用字段value值
      this.cacheFields = []
      this.reservefield.forEach( item => {
        this.cacheFields.push({reservefield_id: item.id, reservefield_value: ''})
      })
    }
  },
  created: function() {
    this.initField();
  }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.organize {
  border: 1px solid #e5e5e5;
  margin: 25px;
}
.organize_dept {
  padding: 20px;
  .dept_title {
    font-size: 20px;
    font-weight: bold;
  }
  .company_name {
    font-size: 14px;
    color: #a0a0a0;
  }
  .ali-jiantou {
    color: #3a3a3a;
  }
  .dept_name {
    font-size: 15px;
  }
}
.organize_tag {
  padding: 10px 0;
  .organize_bottom {
    border-bottom: 1px solid #e5e5e5;
  }
  .tag_btn {
    width: 100%;
    padding: 10px 15px;
    span {
      float: left;
      color: #a0a0a0;
      font-size: 15px;
    }
    i {
      float: right;
      color: #a0a0a0;
      font-size: 18px;
    }
  }
}
.load_more {
  color: #01a0ef;
  padding-bottom: 15px;
  .more_btn {
    font-size: 15px;
    color: #01a0ef;
  }
  .ali-iconfontjiantou {
    font-size: 15px;
  }
}

.ali-bianji {
  color: orange;
  font-size: 23px;
  &:hover {
    cursor: pointer;
  }
}
.organize_title {
  padding: 10px 15px;
  background-color: #f4f6f8;
  span {
    font-size: 18px;
  }
  .btn {
    float: right;
    margin-right: 10px;
  }
}
/* 编辑人员 */
.edit_person {
  i {
    font-size: 80px;
  }
  img {
    width: 80px;
    border-radius: 5px;
  }
  span {
    font-weight: bold;
  }
}
</style>
